<template>
  <el-dialog v-model="visible" :title="query?.title" width="1000" draggable :before-close="isClosed" :close-on-click-modal="false" append-to-body>
    <el-form label-width="auto" :model="formData" ref="formRef" :rules="pageData.businessRules" :inline="true">
      <el-form-item label="商品名称：" prop="product_name" style="width: 46%">
        <el-input placeholder="请输入商品名" v-model="formData.product_name"/>
      </el-form-item>
      <div class="specification-box">
        <el-form-item label="型号类别：" style="width: 96%">
          <el-radio-group v-model="formData.isSpecificationType">
            <el-radio v-for="(item, index) in pageData.specificationType" :key="index" :label="item.label" :value="Number(item.value)"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.isSpecificationType == 1" v-for="item in pageData.board" :key="item.value" :label="item.label" style="width: 30%">
          <el-input-number v-model="item.data" controls-position="right">
            <template #suffix>
              <span>mm</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item v-if="formData.isSpecificationType == 2" v-for="item in pageData.pipe" :key="item.value" :label="item.label" style="width: 30%">
          <el-input-number v-model="item.data" controls-position="right">
            <template #suffix>
              <span>mm</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item v-if="formData.isSpecificationType == 3" v-for="item in pageData.stick" :key="item.value" :label="item.label" style="width: 30%">
          <el-input-number v-model="item.data" controls-position="right">
            <template #suffix>
              <span>mm</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item v-if="formData.isSpecificationType == 4" v-for="item in pageData.Lens" :key="item.value" :label="item.label" style="width: 30%">
          <el-input-number v-model="item.data" controls-position="right">
            <template #suffix>
              <span>mm</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item v-if="formData.isSpecificationType == 5" v-for="item in pageData.ring" :key="item.value" :label="item.label" style="width: 30%">
          <el-input-number v-model="item.data" controls-position="right">
            <template #suffix>
              <span>mm</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item v-if="formData.isSpecificationType == 6" v-for="item in pageData.needle" :key="item.value" :label="item.label" style="width: 30%">
          <el-input-number v-model="item.data" controls-position="right">
            <template #suffix>
              <span>mm</span>
            </template>
          </el-input-number>
        </el-form-item>
          <el-form-item v-if="formData.isSpecificationType == 7" v-for="item in specFields" :key="item.prefix" :label="item.displayName" style="width: 29%">
            <el-input v-if="item.dataType == 'string'" v-model="others[item.prefix]" @blur="handleInputBlur(item)">
              <template #prepend>
                <span>{{ item.prefix }}</span>
              </template>
            </el-input>
            <el-input-number v-if="item.dataType == 'int' || item.dataType == 'double'" v-model="others[item.prefix]" controls-position="right" @blur="handleInputBlur(item)">
              <template #prefix>
                <span>{{ item.prefix }}</span>
              </template>
            </el-input-number>
          </el-form-item>
      </div>
      <el-form-item label="牌号/款式：" style="width: 46%" prop="brand_or_style">
        <el-input placeholder="请输入商品牌号/款式" v-model="formData.brand_or_style" maxlength ="50"/>
      </el-form-item>
      <el-form-item label="内部牌号：" style="width: 46%" prop="internal_brand">
        <el-input placeholder="请输入商品牌号/款式" v-model="formData.internal_brand" maxlength ="50"/>
      </el-form-item>
      <el-form-item label="产品类别：" prop="type" style="width: 46%">
        <el-radio-group v-model="formData.type">
          <el-radio v-for="(item, index) in pageData.productType" :key="index" :label="item.label" :value="Number(item.value)"></el-radio>
        </el-radio-group>
        <el-popover
            class="type-box"
            title="计量方式："
            placement="top-start"
            :width="400"
          >
            <el-table :data="pageData.gridData">
              <el-table-column width="70" property="productType" label="类型" />
              <el-table-column width="110" property="method" label="计量方式" />
              <el-table-column width="300" property="example" label="示例" />
            </el-table>
            <template #reference>
              <el-icon style="margin-left: 10px"><InfoFilled /></el-icon>
            </template>
        </el-popover>
      </el-form-item>
      <el-form-item label="计价方式：" prop="isNumOrWeight" style="width: 46%">
        <el-radio-group v-model="formData.is_quantity_based">
          <el-radio v-for="(item, index) in pageData.NumOrWeight" :key="index" :label="item.label" :value="Number(item.value)" :disabled="is_quantity_based_disabled"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="formData.is_quantity_based == 0" label="单价（按重量计）：" style="width: 46%" prop="unit_price">
        <el-input placeholder="请输入金额" v-model="formData.unit_price" style="width: 70%"/>
        <el-select placeholder="单位" v-model="formData.priceUnit" style="width: 30%">
          <el-option v-for="(item, index) in pageData.priceWeightUnit" :key="index" :label="item.label" :value="String(item.label)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.is_quantity_based == 1" label="单价（按数量计）：" style="width: 46%" prop="unit_price">
        <el-input placeholder="请输入金额" v-model="formData.unit_price" style="width: 70%"/>
        <el-select placeholder="单位" v-model="formData.priceUnit" style="width: 30%">
          <el-option v-for="(item, index) in pageData.priceQuantityUnit" :key="index" :label="item.label" :value="String(item.label)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.type == 1 || formData.type == 3" label="总商品重量需求：" style="width: 46%" :error="weightQuantityError" prop="totalProductWeight">
        <el-input placeholder="商品重量" v-model="formData.totalProductWeight" maxlength ="50" style="width: 70%" show-word-limit/>
        <el-select placeholder="单位" v-model="formData.weightUnit" style="width: 30%">
          <el-option v-for="(item, index) in pageData.weightUnit" :key="index" :label="item.label" :value="String(item.label)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.type == 2 || formData.type == 3" label="总商品数量需求：" style="width: 46%" :error="weightQuantityError" prop="totalProductQuantity">
        <el-input placeholder="商品数量" v-model="formData.totalProductQuantity" maxlength ="50" style="width: 70%" show-word-limit/>
        <el-select placeholder="单位" v-model="formData.quantityUnit" style="width: 30%">
          <el-option v-for="(item, index) in pageData.quantityUnit" :key="index" :label="item.label" :value="String(item.label)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="合同签订总价（/元）：" style="width: 46%" prop="productSum">
        <el-input placeholder="请输入金额" v-model="formData.totalProductSum"/>
      </el-form-item>
      <el-form-item label="签订时间：" prop="signingDate" style="width: 46%">
        <el-date-picker v-model="formData.signingDate" type="date" placeholder="选择时间" :size="size" format="YYYY/MM/DD" value-format="YYYY-MM-DD"/>
      </el-form-item>
      <el-form-item label="有效期：" prop="validityPeriod" style="width: 46%">
        <el-input-number v-model="formData.validityPeriod" controls-position="right">
          <template #suffix>
            <span>月</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="费用率R：" style="width: 46%">
        <el-input-number v-model="formData.costRate" controls-position="right">
          <template #suffix>
            <span>%</span>
          </template>
        </el-input-number>
        <el-tooltip
        class="box-item"
        effect="dark"
        content="单位产品库存年维持费用率，由财务计算得出，用于计算理想最佳采购量"
        placement="bottom"
        >
          <el-icon style="margin-left: 10px"><InfoFilled /></el-icon>
        </el-tooltip>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isClosed">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts">
import { defineComponent, onBeforeMount, reactive, toRefs, ref, PropType, watch } from 'vue'
import { businessAdd, businessUpdate, businessDetails, getSpecificationForm } from "../service/api"
import type { ComponentSize, FormInstance, FormRules} from 'element-plus'
import { ElMessage, ElMessageBox } from "element-plus";
import pageData from '../service/pageService'
export default defineComponent({
    name: 'Pagination',
    props: {
      query: {
        type: Object,
        default: () => ({})
      },
      supplierId: {
        type: Number,
      },
      dialogVisible: {
        type: Boolean,
        default: false
      },
      getbusinessList:{
        type:Function,
        default: () => () => {}
      },
      getAllbusiness:{
        type:Function,
        default: () => () => {}
      }
    },
    setup(props,{emit}) {
      const state = reactive({
        btnLoading: false,
        visible: false,
        others:{},
        specFields:[],
        isInitializing: true,//防止dom未加载完就初始化
        is_quantity_based_disabled: false,
        formData:{
          id:null, //后端提供
          type: null, //产品种类 1-原料，2-产品，3-其他
          is_quantity_based: 1, //计价是否按数量 0-按重量 1-按数量
          isSpecificationType:1, //规格类别 1-7类
          product_name: null,
          brand_or_style: null,
          internal_brand: null,
          totalProductQuantity: null,
          totalProductWeight: null,
          priceUnit: null, //计价单位
          weightUnit: null, //计量单位（重量）
          quantityUnit: null, //计量单位（数量）
          unit_price: null,
          totalProductSum: null, //合同签订总价
          board:[],
          pipe:[],
          stick:[],
          Lens:[],
          ring:[],
          needle:[],
          others:{},
          boardJson: null,
          pipeJson: null,
          stickJson: null,
          lensJson: null,
          ringJson: null,
          needleJson: null,
          signingDate: null, //签订时间
          validityPeriod: null, //有效期
          costRate: null, //单位产品库存年维持费用率
          specification: null,
        }
      })
      const formRef = ref<FormInstance>()
      const isClosed = () =>{
        state.visible = false
        emit('updateData', state.visible)
      }
      watch(() => props.dialogVisible, () => {
        state.visible = props.dialogVisible
        state.isInitializing = true
        initData()
        // 确保数据完全加载
        setTimeout(() => {
          state.isInitializing = false
        }, 500)
        console.log("query",props.query)
      })
      //初始化数组函数
      const resetData = (arr) => {
        arr.forEach(item => {
          item.data = null
        })
      }
      // 预先初始化 others 字段
      const initOthers = () => {
        state.others = {}
      }
      // 独立验证重量和数量
      const weightQuantityError = ref('');
      const validateWeightOrQuantity = () => {
        const { totalProductWeight, totalProductQuantity } = state.formData;
        
        if (!totalProductWeight && !totalProductQuantity) {
          return '重量和数量至少填写一项';
        }
        
        return null;
      };
      // 监听重量和数量变化，实时显示错误
      watch([
        () => state.formData.totalProductWeight,
        () => state.formData.totalProductQuantity
      ], () => {
        weightQuantityError.value = validateWeightOrQuantity() || '';
      });
      //监控外部牌号改内部牌号
      watch(() => state.formData.brand_or_style, () => {
        state.formData.internal_brand = state.formData.brand_or_style
      })
      //监听产品类别以决定计量方式
      watch(() => state.formData.type, () => {
        if(state.formData.type == 1) {
          //原料 
          state.formData.is_quantity_based = 0
          state.is_quantity_based_disabled = true
        }else if(state.formData.type == 2) {
          //产品
          state.formData.is_quantity_based = 1
          state.is_quantity_based_disabled = true
        }else {
          //其他
          state.is_quantity_based_disabled = false
        }
      })
      //设置默认时间
      const getCurrentDate = () => {
        // 获取当前日期并格式化为YYYY-MM-DD
        const date = new Date()
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        state.formData.signingDate = `${year}-${month}-${day}`
      }
      //单位换算（用于计算总价）
      const converseUnit = (row) =>{
        console.log("converseUnit",row)
        pageData.unitConversion.unitPrice = null
        pageData.unitConversion.amount = null
        pageData.unitConversion.piece = null
        if(row?.is_quantity_based == 0 && row?.priceUnit == "元/g"){
          pageData.unitConversion.unitPrice = row?.unit_price*1000
        }else if(row?.is_quantity_based == 0 && row?.priceUnit == "元/kg"){
          pageData.unitConversion.unitPrice = row?.unit_price
        }else if(row?.is_quantity_based == 0 && row?.priceUnit == "元/T"){
          pageData.unitConversion.unitPrice = row?.unit_price/1000
        }
        if(row?.is_quantity_based == 1 && row?.priceUnit == "元/pcs"){
          pageData.unitConversion.unitPrice = row?.unit_price
        }else if(row?.is_quantity_based == 1 && row?.priceUnit == "元/kpcs"){
          pageData.unitConversion.unitPrice = row?.unit_price/1000
        }
        if(row?.totalProductWeight && row?.weightUnit == "g"){
          pageData.unitConversion.amount = row?.totalProductWeight/1000
        }else if(row?.totalProductWeight && row?.weightUnit == "kg"){
          pageData.unitConversion.amount = row?.totalProductWeight
        }else if(row?.totalProductWeight && row?.weightUnit == "T"){
          pageData.unitConversion.amount = row?.totalProductWeight*1000
        }
        if(row?.totalProductQuantity && row?.quantityUnit == "pcs"){
          pageData.unitConversion.piece = row?.totalProductQuantity
        }else if(row?.totalProductQuantity && row?.quantityUnit == "kpcs"){
          pageData.unitConversion.piece = row?.totalProductQuantity*1000
        }
        console.log("单价",pageData.unitConversion.unitPrice)
        console.log("数量",pageData.unitConversion.piece)
        console.log("重量",pageData.unitConversion.amount)
      }
      //监控总价变化
      watch(
        [
          () => state.formData.is_quantity_based,
          () => state.formData.totalProductQuantity,
          () => state.formData.totalProductWeight,
          () => state.formData.unit_price,
          () => state.formData.priceUnit,
          () => state.formData.weightUnit,
          () => state.formData.quantityUnit,
        ],
        (newValues, oldValues) => {
        converseUnit(state.formData)
        if(state.formData.is_quantity_based == 1) state.formData.totalProductSum = +(pageData.unitConversion.unitPrice*pageData.unitConversion.piece).toFixed(2);
        else if(state.formData.is_quantity_based == 0) state.formData.totalProductSum = +(pageData.unitConversion.unitPrice*pageData.unitConversion.amount).toFixed(2);
      })
      //监听数值补充单位
      watch(() => state.formData.is_quantity_based, () => {
        if(state.formData.is_quantity_based == 1 && props.query?.type == 'add') state.formData.priceUnit = '元/pcs'
        else if(state.formData.is_quantity_based == 0 && props.query?.type == 'add') state.formData.priceUnit = '元/kg'
      })
      //监控产品规格类型初始化
      watch(() => state.formData.isSpecificationType, () => {
        if(!state.isInitializing) {
          resetData(pageData.board)
          resetData(pageData.pipe)
          resetData(pageData.stick)
          resetData(pageData.Lens)
          resetData(pageData.ring)
          resetData(pageData.needle)
          initOthers()
        }
      })
      const initData = () => {
        console.log("props.query",props.query)
        getSpecificationForm().then((res)=>{
          state.specFields = res.data.data
          console.log("规格表",state.specFields)
        })
        if(props.query?.type == 'add') {
          state.isInitializing = false
        }
        if(props.query?.type == 'edit') {
          const params = {
            id:props.query?.id
          }
          businessDetails(params).then((res)=>{
            console.log('res',res)
            state.formData = res.data.data
            // 遍历数组，将 state.board 中的值依次赋给 board 中的 data 属性
            if(state.formData.isSpecificationType == 1)
            {
              //板类
              pageData.board.forEach((item, index) => {
                item.data = state.formData.board[index];
              })
            }else if(state.formData.isSpecificationType == 2)
            {
              //管类
              pageData.pipe.forEach((item, index) => {
                item.data = state.formData.pipe[index];
              })
            }else if(state.formData.isSpecificationType == 3)
            {
              //棒类
              pageData.stick.forEach((item, index) => {
                item.data = state.formData.stick[index];
              })
            }else if(state.formData.isSpecificationType == 4)
            {
              //镜类
              pageData.Lens.forEach((item, index) => {
                item.data = state.formData.Lens[index];
              })
            }else if(state.formData.isSpecificationType == 5)
            {
              //环类
              pageData.ring.forEach((item, index) => {
                item.data = state.formData.ring[index];
              })
            }else if(state.formData.isSpecificationType == 6)
            {
              //点焊针类
              pageData.needle.forEach((item, index) => {
                item.data = state.formData.needle[index];
              })
            }else if(state.formData.isSpecificationType == 7)
            {
              //其他类
              state.others = state.formData.others
            }
          }).catch((error) => {
            console.error('无法获取数据', error);
          });
        }else if (props.query?.type == 'add') {
          //初始化表单
          state.formData = JSON.parse(JSON.stringify(pageData.initBusinessData))
          resetData(pageData.board)
          resetData(pageData.pipe)
          resetData(pageData.stick)
          resetData(pageData.Lens)
          resetData(pageData.ring)
          resetData(pageData.needle)
          initOthers()
          getCurrentDate()
          state.formData.quantityUnit = "pcs"
          state.formData.weightUnit = "kg"
        }
      }
      const submit = () => {
        state.btnLoading = true
        if(state.formData.isSpecificationType == 1 && pageData.board.every(item => item.data)) {
          state.formData.board = pageData.board.map(item => item.data)
          state.formData.specification = "L"+state.formData.board[0]+"*"+"W"+state.formData.board[1]+"*"+"T"+state.formData.board[2]
          state.formData.boardJson = JSON.stringify(state.formData.board)
        }
        else if(state.formData.isSpecificationType == 2 && pageData.pipe.every(item => item.data)){
          state.formData.pipe = pageData.pipe.map(item => item.data)
          state.formData.specification = "D"+state.formData.pipe[1]+"*"+"d"+state.formData.pipe[2]+"*"+"L"+state.formData.pipe[0]
          state.formData.pipeJson = JSON.stringify(state.formData.pipe)
        }
        else if(state.formData.isSpecificationType == 3 && pageData.stick.every(item => item.data)){
          state.formData.stick = pageData.stick.map(item => item.data)
          state.formData.specification = "D"+state.formData.stick[1]+"*"+"L"+state.formData.stick[0]
          state.formData.stickJson = JSON.stringify(state.formData.stick)
        } 
        else if(state.formData.isSpecificationType == 4 && pageData.Lens.every(item => item.data)){
          state.formData.Lens = pageData.Lens.map(item => item.data)
          state.formData.specification = "D"+state.formData.Lens[0]+"*"+"W"+state.formData.Lens[1]
          state.formData.LensJson = JSON.stringify(state.formData.Lens)
        } 
        else if(state.formData.isSpecificationType == 5 && pageData.ring.every(item => item.data)){
          state.formData.ring = pageData.ring.map(item => item.data && pageData.ring.every(item => item.data))
          state.formData.specification = "D"+state.formData.ring[0]+"*"+"d"+state.formData.ring[1]
          state.formData.ringJson = JSON.stringify(state.formData.ring)
        } 
        else if(state.formData.isSpecificationType == 6 && pageData.needle.every(item => item.data)){
          state.formData.needle = pageData.needle.map(item => item.data)
          state.formData.specification = "L"+state.formData.needle[0]+"*"+"D"+state.formData.needle[1]+"*"+"Φ"+state.formData.needle[2]
          state.formData.needleJson = JSON.stringify(state.formData.needle)
        }
        else if(state.formData.isSpecificationType == 7 && Object.keys(state.others).length > 0){
          state.formData.others = state.others
          state.formData.specification = ''
          Object.keys(state.formData.others).forEach(prefix => {
            // 检查属性是否为自有属性且值不为空
            if (state.formData.others.hasOwnProperty(prefix) && state.formData.others[prefix]) {
              // 将前缀和值组合，并用 * 连接
              state.formData.specification =  state.formData.specification + `${prefix}${state.formData.others[prefix]}` + "*"
            }
          })
          state.formData.specification = state.formData.specification.slice(0, -1)
        }else {
          state.formData.specification = null
        }
        console.log("state.formData",state.formData)
        const error = validateWeightOrQuantity();
        if (error) {
          weightQuantityError.value = validateWeightOrQuantity() || '';
          ElMessage.error(error);
          return;
        }
        formRef.value.validate((valid) => {
          console.log("valid",valid)
          if (valid) { 
              // 验证通过
            if(props.query.type == 'edit'){
              businessUpdate(props.query?.id, props.supplierId ,state.formData).then((res)=>{
                ElMessage.success("保存成功！")
                props.getbusinessList()
                isClosed(); // 关闭弹窗
                state.btnLoading = false
              })
            }else if(props.query.type == 'add'){
              businessAdd(props.supplierId , state.formData).then((res)=>{
                ElMessage.success("保存成功！")
                props.getbusinessList()
                props.getAllbusiness()
                isClosed(); // 关闭弹窗
                state.btnLoading = false
              })
            }
          }else {
            ElMessage.error('请完成必填字段')
          }
        })
      }
      onBeforeMount(() => {
        //state.visible = props.dialogVisible
      })
      return {
        ...toRefs(state),
        isClosed,
        formRef,
        pageData,
        submit,
        weightQuantityError
      }
    }
})
</script>
<style scoped>
.layout{
    width: auto;
    height: 800px;
    background-color: #FFFFFF;
}
.specification-box {
  background-color: #f5f7fa;
  margin-bottom: 10px;
  max-height: 150px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示竖向滚动条 */
}

.tooltip-base-box {
  width: 600px;
}
.tooltip-base-box .row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tooltip-base-box .center {
  justify-content: center;
}
.tooltip-base-box .box-item {
  width: 110px;
  margin-top: 10px;
}
</style>
  